package newpostman.pojo;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import utils.JsonObjectUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Yan on 2018/4/3.
 */
public class ExportNewPostManApiUtil {

    public static String readToString(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long fileLength = file.length();
        byte[] fileContent = new byte[fileLength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(fileContent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(fileContent, encoding);
        } catch (UnsupportedEncodingException e) {
            System.err.println("The OS does not support " + encoding);
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        readFile("F:\\sy_system.postman_collection.json");
    }

    /**
     * 解析postman 导出的Json数据
     *
     * @param path
     */
    private static void readFile(String path) {
        String file = readToString(path);
        JSONObject  jsonTreeObj = JSONObject.fromObject(file);
        JsonNode jsonTree = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            jsonTree = objectMapper.readTree(jsonTreeObj.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }



        JsonNode infoTree = jsonTree.get("info");
if(infoTree==null){
    return;
}

        //获得json树
        String projectName = infoTree.get("name").toString();//获得项目名称
        String projectDesc = infoTree.get("description").toString();//获得项目名称

        Info info = new Info(projectName,projectDesc);


        //获得模块列表
        List<Model> modelList = new ArrayList<>();
        JsonNode modelListJson = jsonTree.get("item");
        for (JsonNode  mo : modelListJson) {
            Model model = new Model();
            model.setName(mo.get("name").toString());
//获得接口列表
            JsonNode itemListJson = mo.get("item");

            List<Item> itemList = new ArrayList<>();
            for (JsonNode io : itemListJson) {
                Item item = new Item();
                item.setName(io.get("name").toString());
               //获得url method等属性，存在request中
                JsonNode reqo = io.get("request");
                JsonNode exampleListJson = io.get("response");
                String method = reqo.get("method").toString().replaceAll("\"","");

                item.setMethod(method);
                item.setUrl(reqo.get("url").get("raw").toString());
                JsonNode header  = reqo.get("header");





                if(header!=null) {
                    if (header.isArray()) {

                        for (JsonNode objNode : header) {
                                JsonNode valueNode = objNode.get("value");
                                    if(valueNode!=null) {
                                        item.setHeader(valueNode.toString());
                                        break;
                                    }

                            }
                               // break;

                        }
                    }


                JsonNode description = reqo.get("description");
                if(description!=null) {
                    item.setDescription(description.toString());
                }
                //请求参数 转换，
                JsonNode descriptListJsno = null;
                //if(method.equals("POST")||method.equals("post")) {
                    //
                String mode = null;
                JsonNode body = null;
                if(method.equals("GET")||method.equals("get")) {
                    descriptListJsno = reqo.get("url").get("query");
                }else{
                    body = reqo.get("body");
                     mode = body.get("mode").toString().replaceAll("\"","");
                     switch (mode){
                         case "formdata":
                             descriptListJsno = body.get("formdata");
                             break;
                         case "urlencoded":
                             descriptListJsno = body.get("urlencoded");
                             break;
                         case "raw":
                             descriptListJsno = body.get("raw");
                             break;
                         default:;
                     }
                }


                itemList.add(item);//添加到模块
                if(descriptListJsno !=null){
                    List<Descript> descriptList = new ArrayList<>();

                        for (JsonNode dco : descriptListJsno) {
                            Descript descript = new Descript();
                            JsonObjectUtils.copyJsonToObject(dco, descript);
                            if (item.getMethod().equals("GET")) {
                                descript.setType("text");
                            }
                            descriptList.add(descript);
                        }
                    item.setDescriptList(descriptList);
                }
                if(exampleListJson != null){
                    List<Example> exampleList = new ArrayList<>();
                    for (JsonNode elo : exampleListJson) {

                        Example example = new Example();
                        example.setName(elo.get("name").toString());
                        JsonNode headerList  = elo.get("header");

                        if(headerList!=null) {
                                example.setHeader(headerList.toString());
                        }

                        if(elo.get("status")!=null) {
                            example.setStatus(elo.get("status").toString());
                        }
                        if(elo.get("code")!=null) {
                            example.setCode(elo.get("code").toString());
                        }
                        JsonNode originalRequest = elo.get("originalRequest");


                        JsonNode url = originalRequest.get("url");
                        example.setUrl(url.get("raw").toString());
                        JsonNode jsonNode = url.get("query");
                        if(jsonNode!=null) {
                            example.setQuery(url.get("query").toString());
                        }

                        JsonNode examplebody = elo.get("body");

                        example.setMethod(originalRequest.get("method").toString());
if(examplebody!=null) {
    JsonNode msg = examplebody.get("msg");
    if(msg!=null) {
        example.setMsg(msg.toString());
    }
        if (examplebody != null) {

            example.setData(examplebody.toString().replaceAll("\"", "'"));
        }
    }

                        exampleList.add(example);
                    }
                    item.setExampleList(exampleList);
                }

            }

           model.setItemList(itemList);
            modelList.add(model);
        }
       info.setModelList(modelList);
        writeToHtml(info);
    }

    /**
     * 数据拼成html
     *
     * @param info
     */
    private static void writeToHtml(Info info) {

        StringBuilder builder = new StringBuilder();
        builder.append("<style>" +
                "ul{margin-left:30px;}" +
                "li{left:20px;list-style-type:none;padding-bottom:10px;}table{margin-top:10px;}" +
                "td{height:30px;line-height:30px; Word-break: break-all;}" +
                "h3{left:20px;padding-bottom:10px;position:relative;}h4{left:40px;padding-bottom:10px;position:relative;}" +
                "td > span{display:inline-block;margin-left:20px;}" +
                        ".paramTable tr:nth-child(1){background-color:#517d69;text-align:center;color:#f1f1f1;}"+
                ".modelName{color:#795548;}"+
                ".itemName{color:#9e4854;}"+
                        ".addressTitle{color:#f44336;font-size:16}"+
                        ".addressContent{color:#48829e;}"+
                ".descriptionTitle{color:#48829e;font-size:18}"+
                        ".descriptionContent{padding-top:20px;padding-left:60px;color:#a5273e;font-size:16}"+



                ".tdspan1{width:120}.tdspan2{width:110}.tdspan3{width:240}.tdspan4{width:400}" +
                ".liExampleTitle{color:green;font-size:18;margin-top:10px;margin-bottom:10px;}"+
                ".liExample{margin-top:10px;margin-bottom:10px;}.exampleTd{width:120px;}"+
                ".exampleName{font-size:16;color:#795548;}"+
                ".urlSpan{display:inline-block;width:40;font-size:14;padding:10 5 10 5;color:#c72a4e;}"+
                ".urlSpanContent{font-size:14;color:#FF5722;}.exampleSpan{color:#45942a}" +
                ".exampleTable{border-color:#9E9E9E;color:rgb(31, 30, 30)}"+
                ".exampleTable tr:nth-child(odd){background-color:rgba(15, 113, 156, 0.48);}"+
                ".exampleVal span{padding-right:15px;}"+
                "</style>");
        builder.append("<h2>" + info.getName() + "</h2>");
        builder.append("<br/>");
        int i = 0;
        for (Model model : info.getModelList()) {
            i++;
            List<Item> itemList = model.getItemList();
            builder.append("<h3 style='margin:1px 0 1px 0'><span class='modelName'>" + i + ". 模块名称：" + model.getName() + "</span></h3>");
            int j = 0;
            for (Item item : itemList) {
                j++;
                builder.append("<h4 style='margin:1px 0 1px 0'><span class='itemName'>" + i + "." + j + " 接口名称：" + item.getName() + "</h4>");
                builder.append("<ul>");


                builder.append("<li style='margin:1px 0 1px 0'><span class='addressTitle'>接口地址：</span><span class='addressContent'>"
                        + item.getUrl() + "</span></li>");
               builder.append("<li style='margin:1px 0 1px 0'>请求方式：" + item.getMethod() + "</li>");
                builder.append("<li style='margin:1px 0 1px 0'>请求头：" + item.getHeader() + "</li>");
                builder.append("<li><span class='descriptionTitle'>说明：<span><br/>"
                        +"<span class='descriptionContent'>"+item.getDescription()+"</span></li>");
                List<Descript> descriptList = item.getDescriptList();
                if (descriptList!= null && descriptList.size() > 0) {
                    builder.append("<li><div> <style='margin:1px 0 1px 0'>请求参数：</div>");


                    builder.append("<div><table class='paramTable' border=\"1\" cellspacing=\"0\" cellpadding=\"0\">");
                    builder.append("<tr>");
                    builder.append("<td>参数名</td><td>参数类型</td><td>示例值</td><td>描述</td>");
                    builder.append("</tr>");
                    for (Descript descript : descriptList) {
                        builder.append("<tr>");
                        builder.append("<td><span class='tdspan1'>" + descript.getKey() + "</span></td>" +
                                "<td><span class='tdspan2'>" + descript.getType() + "</span></td>" +
                        "<td><span class='tdspan3'>" + descript.getValue() + "</span></td>"+
                        "<td><span class='tdspan4'>" + descript.getDescription() + "</span></td>");
                        builder.append("</tr>");
                    }
                    builder.append("</table></div>");
                    builder.append("</li>");

                    List<Example> exampleList = item.getExampleList();
                    if (exampleList!=null && exampleList.size() > 0) {
                        builder.append("<li class='liExampleTitle'>示例</li>");
                        for (Example example : exampleList) {
                            //builder.append(example.getName());
                            builder.append("<li class='liExample'>");
                                    builder.append("<div class='exampleName'> <style='margin:1px 0 1px 0'>"+example.getName()+"</div>");
                            builder.append("<div><span class='urlSpan'>url:</span><style='margin:1px 0 1px 0'><span class='urlSpanContent'>"+example.getUrl()+"</span></div>");
                            builder.append("<div><table class='exampleTable' border=\"1\" cellspacing=\"0\" cellpadding=\"0\">");
                            builder.append("<tr><td class='exampleTd'><span class='exampleSpan'>header</span></td><td class='exampleVal'><span>" + example.getHeader() + "</span></td></tr>" +
                            "<tr><td><span class='exampleSpan'>method</span></td><td><span>" + example.getMethod() + "</span></td></tr>" +
                                    "<tr><td><span class='exampleSpan'>code</span></td><td><span>" + example.getCode() + "</span></td></tr>" +
                                    "<tr><td><span class='exampleSpan'>msg</span></td><td><span>" + example.getMsg() + "</span></td></tr>" +
                                            "<tr><td><span class='exampleSpan'>queryParma</span></td><td><span>" + example.getQuery() + "</span></td></tr>"+
                                    "<tr><td><span class='exampleSpan'>returnValue</span></td><td><pre>"
                                    +"<script>"
                                            + "document.write(JSON.stringify(\""
                                    +example.getData()
                                    +"\", null, '\t'));"




                                   + "</script>"
                                    +"</pre></td></tr>");
                            builder.append("</tr>");
                            builder.append("</table></div>");
                            builder.append("</li>");
                        }

                    }
                }
                builder.append("</li></ul>");
            }

        }
        System.out.println(builder.toString());
        File file = new File("f://1.html");
        FileWriter fw = null;
        try {
            fw = new FileWriter(file);
            fw.write(builder.toString().replaceAll("\"",""));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fw.flush();
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}
